package it.trekker.dataexchange;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import it.trekker.db.Poi;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.SerializedName;

public class PoiRealTimeInfo {

	@SerializedName("poi")
	private Poi poi;

	@SerializedName("distance-to-goal")
	private double distanceToGoal;

	@SerializedName("mean-pace")
	private double meanPace;


	public PoiRealTimeInfo() {
	}


	public Poi getPoi() {
		return poi;
	}


	public void setPoi(Poi poi) {
		this.poi = poi;
	}


	public double getDistanceToGoal() {
		return distanceToGoal;
	}


	public void setDistanceToGoal(double distanceToGoal) {
		this.distanceToGoal = distanceToGoal;
	}


	public double getMeanPace() {
		return meanPace;
	}


	public void setMeanPace(double meanPace) {
		this.meanPace = meanPace;
	}


	@Override
	public String toString() {
		return String.format(
				"Goal (latitude: %f, longitude: %f, altitude: %f); " +
						"distance: %.3f, meanPace: %.3f", 
						poi.getLocation().getLatitude(), poi.getLocation().getLongitude(), 
						poi.getLocation().getAltitude(), distanceToGoal, meanPace);
	}


	@Override
	public boolean equals(Object o) {
		if(o == null)
			return false;
		if(this == o)
			return true;
		if(!(o instanceof PoiRealTimeInfo))
			return false;

		PoiRealTimeInfo other = (PoiRealTimeInfo) o;

		if(!this.poi.equals(other.poi))
			return false;

		return true;
	}


	
	
	
	
	// For Gson: to avoid problems with Date serialization/deserialization

	private static final String dateFormat = "MM/dd/yyyy hh:mm:ss a";
	private static SimpleDateFormat format = new SimpleDateFormat(dateFormat);

	private static class DateTimeSerializer implements JsonSerializer<Date> {
		@Override
		public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
			return new JsonPrimitive(format.format(src));
		}
	}

	private static class DateTimeDeserializer implements JsonDeserializer<Date> {
		@Override
		public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
			try {
				return format.parse(json.getAsJsonPrimitive().getAsString());
			} catch (ParseException e) {
				throw new JsonParseException(e.getMessage());
			}
		}
	}

}
